import { login, getUsrInfo, getUesrData } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: {}
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 这个longin是actions的属性
  async login(store, fromData) {
    const res = await login(fromData)
    // console.log(res)
    store.commit('setToken', res)
  },
  async getUsrInfo(store) {
    const res2 = await getUsrInfo()
    const data = await getUesrData(res2.userId)
    // console.log(res2)
    store.commit('setUserInfo', { ...res2, ...data })
  },
  logout(store) {
    resetRouter()
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

